package com.yuyou.fn.exception;

import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.controller.ReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by wens on 2017/2/19.
 */
public class DefaultExceptionResolver implements HandlerExceptionResolver {

    private final Logger logger = LoggerFactory.getLogger(DefaultExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {

        logger.error("Request Fail:" + httpServletRequest.getRequestURI(), ex);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        try {
            PrintWriter writer = httpServletResponse.getWriter();
            if(ex instanceof BusException){
                BusException e = (BusException) ex ;
                writer.write(ReturnResult.fail(e.getMessage()).toJsonString());
            }else{
                writer.write(ReturnResult.fail("Server Error").toJsonString());
            }
            return new ModelAndView();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
